<template>
  <div class='preview-image'>
    <img :src="image" ref="image" class="image">
    <van-nav-bar
      class="bottomBar"
      left-text="返回"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onComplete"
    />
  </div>
</template>

<script>
import { updateUserImage } from '@/api/user'
import { Toast } from 'vant'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

export default {
  name: 'PreviewImage',
  components: {},
  props: {
    imageFile: {
      required: true
    }
  },
  data () {
    return {
      image: window.URL.createObjectURL(this.imageFile),
      cropper: null
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {
    // 配置裁剪图片
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    // 封装的裁剪图片的方法，方便使用异步
    getCroppedCanvas () {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          resolve(blob)
        })
      })
    },
    async onComplete () {
      Toast.loading({
        message: '上传中',
        forbidClick: true
      })
      const file = await this.getCroppedCanvas()
      const fd = new FormData()
      fd.append('photo', file)
      await updateUserImage(fd)
      Toast.success('修改成功')
      this.$emit('update-image', window.URL.createObjectURL(file))
      this.$emit('close')
    }
  }
}
</script>
<style lang='less' scoped>
.bottomBar {
  position: fixed;
  bottom: 0;
  right: 0;
  left: 0;
}
.image {
  display: block;
  max-width: 100%;
}
</style>
